import {
  PlusOutlined,
  TagsOutlined,
  MoreOutlined,
  DeleteOutlined,
  QuestionCircleOutlined,
  LoadingOutlined,
  CheckCircleTwoTone,
  CloseCircleTwoTone
} from '@ant-design/icons';
import { Button, Divider, message, Input, Select, Modal, Tag, AutoComplete, Avatar, Spin } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import debounce from 'lodash.debounce';
import { history } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import CreateForm from './components/CreateForm';
import PreviewModel from './components/PreviewModel';
import TagCommonComponent from '../System/components/TagCommonComponent';
import AssignTagsModel from '../System/components/AssignTagsModel';
import PlanModel from './components/PlanModel';
import { repackPlan } from '../Plan/service';
import { TableListItem } from './data.d';
import {
  programList,
  programAdd,
  programRemove,
  batchDelete,
  programCopy,
  programUpdate,
  setTag,
  programDetail,
} from './service';
import styles from './index.less';

const { Search } = Input;
const { Option } = Select;
const antIcon = <LoadingOutlined style={{ fontSize: 12 }} spin />;

const NoticeList: React.FC<{}> = () => {
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  const [previewModalVisible, handlePreviewModalVisible] = useState<boolean>(false);
  const [deleteModalVisible, handleDeleteModalVisible] = useState<boolean>(false);
  const [publishModalVisible, handlePublishModalVisible] = useState<boolean>(false);
  const [planModalVisible, handlePlanModalVisible] = useState<boolean>(false);
  const [formValues, setFormValues] = useState<TableListItem>({});
  const actionRef = useRef<ActionType>();
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const [selectedRows, setSelectedRows] = useState<TableListItem[]>([]);
  const [tagEnabled, handleTagEnabled] = useState<boolean>(true);
  const [topOrgId, setTopOrgId] = useState<number>(0);
  const [assignTagModalVisible, handleAssignTagModalVisible] = useState<boolean>(false);

  const [repackPlanList, setRepackPlanList] = useState<Array<any>>([]); //循环时间段列表 -- 按时段播放
  const [repackModalVisible, handleRepackModalVisible] = useState<boolean>(false);
  const [repackFinish, handleRepackFinish] = useState<boolean>(false);

  const [programId, setProgramId] = useState<number>(0);

  const tagControl = () => {
    if (selectedRowKeys.length > 0) {
      for (let i in selectedRows) {
        if (parseInt(i) > 0) {
          const row1 = selectedRows[parseInt(i) - 1];
          const row = selectedRows[i];
          if (row1.topOrgId != row.topOrgId) {
            handleTagEnabled(true);
            return;
          }
        }
      }
      setTopOrgId(selectedRows[0].topOrgId);
      handleTagEnabled(false);
    } else {
      handleTagEnabled(true);
    }
  }

  useEffect(() => {
    tagControl();
  }, [selectedRowKeys, selectedRows]);

  const repackPlanRequest = (list: Array<any>) => {
    // const promiseArray = new Array;//动态循环创建promise
    // for(let i in list){
    //     const id = list[i].id;
    //     const index = parseInt(i);
    //     promiseArray.push(repackPlan(id).then(res=>{
    //         if(res && res.code === 200){
    //             list[index].status = "success";
    //         }else{
    //             list[index].status = "failed";
    //         }
    //         setRepackPlanList(list.concat());
    //     }))
    // }
    // Promise.all(promiseArray).then(data=> {
    //     handleRepackFinish(true);
    //     localStorage.removeItem("programInfo");
    //     localStorage.removeItem("planUpdate");
    // });
    let resList = new Array;
    function startRequest() {
      //定义counts，用来收集请求的次数，（也可以用resList的length进行判断）
      let counts = 0;
      return function requestFunc() {
        if (counts == list.length) {
          handleRepackFinish(true);
          localStorage.removeItem("programInfo");
          localStorage.removeItem("planUpdate");
          return;
        }
        let arg = list[counts].name;
        let a = new Promise((res, rej) => {
          const id = list[counts].id;
          repackPlan(id).then(result => {
            if (result && result.code === 200) {
              list[counts].status = "success";
              res(true);
            } else {
              list[counts].status = "failed";
              res(false);
            }
            setRepackPlanList(list.concat());

          })
        })
        //无论成功或者失败都要进行下一次，以免阻塞，成功请求的末尾有s标志，失败的末尾有f标志
        a.then(() => {
          counts++;
          resList.push(arg + ' s');
          requestFunc(list[counts])
        }).catch(err => {
          // resList.push(arg + 'f');
          //递归调用
          // console.log("======递归调用==========")
          // requestFunc(list[counts])
          console.log(err)
        })
      }
    }
    let start = startRequest();
    start(list[0]);
  }

  useEffect(() => {
    const programInfo = localStorage.getItem("programInfo");
    if (programInfo) {
      const programId = JSON.parse(programInfo)?.id;
      const planUpdate = localStorage.getItem("planUpdate");
      if (planUpdate == "true") {
        if (programId) {
          new Promise((resolve, reject) => {
            programDetail(programId)
              .then((res) => {
                if (res && res.code === 200) {
                  let data = res.data;
                  const list = data.plans;
                  if (list && list.length > 0) {
                    const planList = list.map(item => { return { id: item.id, name: item.name, status: 'spinning' } });
                    if (planList.length > 0) {
                      setRepackPlanList(planList);
                      handleRepackModalVisible(true);
                      repackPlanRequest(planList);
                    }
                  } else {
                    localStorage.removeItem("programInfo");
                    localStorage.removeItem("planUpdate");
                  }
                  resolve(true);
                } else {
                  message.error('请求失败，' + res.message);
                  resolve(false);
                }
              })
              .catch((error) => {
                message.error('请求失败');
                reject(error);
              });
          });
        }
      } else {
        localStorage.removeItem("programInfo");
        localStorage.removeItem("planUpdate");
      }
    } else {
      localStorage.removeItem("planUpdate");
    }
  }, []);

  //标签选中监听
  const selectChange = (values: any, form: any) => {
    form.setFieldsValue({ "tagIds": values ? values.toString() : "" });
    form.submit();
  }

  const handleCancel = () => {
    handleModalVisible(false);
  };

  const handleClose = () => {
    handlePreviewModalVisible(false);
    syncArray = [];
    mainTimeAxis = 0;
    var id = window.setTimeout(function () { }, 0);
    while (id--) {
      window.clearTimeout(id);
    } //停止计数器
  };
  //节目删除--删除弹出框
  const delConfirm = (id: number) => {
    const param = new Object();
    param["id"] = id;
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此节目将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          programRemove(param)
            .then((res) => {
              if (res) {
                if (res.code === 200) {
                  const hide = message.success('删除成功');
                  handleDeleteModalVisible(false);
                  if (selectedRowKeys.length > 0) {
                    for (var i in selectedRowKeys) {
                      if (selectedRowKeys[i] == id) {
                        selectedRowKeys.splice(parseInt(i), 1);
                      }
                    }
                  }
                  hide();
                  if (selectedRowKeys.length == 0) {
                    setSelectedRowKeys([]);
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  } else {
                    const newRows = selectedRows.concat();
                    for (let i = 0; i < selectedRows.length; i++) {
                      if (selectedRows[i].id == id) {
                        newRows.splice(i, 1);
                      }
                    }
                    setSelectedRows(newRows);
                    actionRef.current?.reload?.();
                  }
                  resolve(true);
                } else {
                  message.error('删除失败，' + res.message);
                  resolve(false);
                }
              }
            })
            .catch((error) => {
              message.error('删除失败');
              reject(error);
            });
        });
      },
    });
  };
  //节目批量删除
  const delConfirmBatch = (ids: string) => {
    const param = new Object();
    param["ids"] = ids;
    Modal.confirm({
      visible: deleteModalVisible,
      title: '确定删除',
      icon: <QuestionCircleOutlined />,
      content: '此节目将永久删除',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        return new Promise((resolve, reject) => {
          batchDelete(param)
            .then((res) => {
              if (res) {
                if (res.code === 200) {
                  const errList = res.data;
                  if (errList.length == 0) {
                    message.success("删除成功", 1);
                  } else {
                    let mes = "";
                    for (let i in errList) {
                      for (let j in selectedRows) {
                        if (parseInt(selectedRows[j].id) == errList[i]) {
                          mes += selectedRows[j].name + '，';
                        }
                      }
                    }
                    mes = mes + "删除失败";
                    message.error(mes, 2);
                  }
                  handleDeleteModalVisible(false);
                  setSelectedRowKeys([]);
                  setSelectedRows([]);
                  actionRef.current?.reloadAndRest?.();
                  resolve(true);
                } else {
                  message.error('删除失败，' + res.message);
                  resolve(false);
                }
              } else {
                message.error('删除失败');
                resolve(false);
              }
            })
            .catch((error) => {
              message.error('请求失败');
              reject(error);
            });
        });
      },
    });
  };
  //发布功能
  const publishCommand = (items: any) => {
    const programList = [];
    const programIds = [];
    for (let i in items) {
      const item = items[i];
      const programItem = new Object();
      for (let key in item) {
        if (key == "id" || key == "name" || key == "totalTime" || key == "previewImgUrl" || key == "resolution") {
          programItem[key] = item[key];
        }
      }
      programItem["key"] = i;
      programItem["seq"] = i;
      programList.push(programItem);
      programIds.push(item.id)
    }

    const playConfig = [{
      "id": 0,
      "startTime": "08:00:00",
      "endTime": "20:00:00",
      "type": "day",
      programList: programList,
    }];

    const Now = new Date();
    const year = Now.getFullYear();
    const month = Now.getMonth() + 1;
    const day = Now.getDate();
    const hour = Now.getHours();
    const minutes = Now.getMinutes();
    const seconds = Now.getSeconds();
    Now.setTime(Now.getTime());
    const date = year + '-' + (month >= 10 ? month.toString() : "0" + month) + '-' + (day >= 10 ? day.toString() : "0" + day);
    const planName = "Plan" + year.toString() + month.toString() + day.toString() + hour.toString() + minutes.toString() + seconds.toString();

    const planObj = {
      flag: "publish",
      describe: "",
      startDatetime: date + " 00:00:00",
      endDatetime: date + " 23:59:59",
      name: planName,
      playConfig: JSON.stringify(playConfig),
      playMode: 1,
      playStrategy: 0,
      programIds: programIds.toString(),
      publishType: 0,
      publishWay: 0,
    }
    history.push({ pathname: '/plan/list/new', state: planObj });
  }
  //批量发布
  const publishConfirm = (items: any) => {
    Modal.confirm({
      visible: publishModalVisible,
      title: '是否批量发布',
      icon: < QuestionCircleOutlined />,
      content: '所选的节目分辨率若不一致，将影响终端播放效果，是否确认发布？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => {
        publishCommand(items)
      },
    });
  }
  //发布
  const publish = (item: TableListItem) => {
    publishCommand([item])
  }

  //节目复制
  const copy = (id: number) => {
    new Promise((resolve, reject) => {
      programCopy(id)
        .then((res) => {
          if (res) {
            if (res.code === 200) {
              const hide = message.success('复制成功');
              // setSelectedRows([]);
              if (actionRef.current) {
                hide();
                actionRef.current.reload();
              }
              resolve(true);
            } else {
              message.error('复制失败，' + res.message);
              resolve(false);
            }
          }
        })
        .catch((error) => {
          message.error('复制失败');
          reject(error);
        });
    });
  };

  //节目设计
  const design = (item: TableListItem) => {
    let id = item.id;
    if (id) {
      let programInfo = new Object();
      programInfo['id'] = id;
      programInfo['name'] = item.name;
      programInfo['deviceType'] = item.deviceType;
      programInfo['resolutionWidth'] = item.resolutionWidth;
      programInfo['resolutionHeight'] = item.resolutionHeight;
      // programInfo['template'] = item.template;
      programInfo['type'] = 'edit';
      // programInfo['idUrlMaps'] = item["id-url-maps"];
      let storage = window.localStorage;
      storage['programInfo'] = JSON.stringify(programInfo);
      history.push('/programEditor'); //跳转到编辑页面
    }
  };

  //新建节目
  const addProgram = (params: Object) => {
    new Promise((resolve, reject) => {
      programAdd(params)
        .then((res) => {
          if (res.code === 200) {
            let programInfo = new Object();
            programInfo["id"] = res.data;
            programInfo['name'] = params.name;
            programInfo['deviceType'] = params.deviceType;
            programInfo['resolutionWidth'] = params.resolutionWidth;
            programInfo['resolutionHeight'] = params.resolutionHeight;
            // programInfo['template'] = item.template;
            programInfo['type'] = 'edit';
            let storage = window.localStorage;
            storage['programInfo'] = JSON.stringify(programInfo);
            history.push('/programEditor'); //跳转到编辑页面
            resolve(true);
          } else if (res.code == 4501) {
            message.error('节目使用中，不能修改');
            resolve(false);
          } else {
            message.error('修改失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  };

  //编辑节目保存
  const save = (params: Object) => {
    new Promise((resolve, reject) => {
      programUpdate(params)
        .then((res) => {
          if (res.code === 200) {
            message.success('修改成功');
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            resolve(true);
          } else if (res.code == 4501) {
            message.error('节目使用中，不能修改');
            resolve(false);
          } else {
            message.error('修改失败');
            resolve(false);
          }
        })
        .catch((error) => {
          message.error('请求失败');
          reject(error);
        });
    });
  };

  //读取js文件
  const readTextFile = (file: any) => {
    let str = "";
    let rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
      if (rawFile.readyState === 4) {
        if (rawFile.status === 200 || rawFile.status == 0) {
          str = rawFile.responseText;
        }
      }
    }

    rawFile.send(null);
    return str;
  }

  //【新建/编辑】对话框，确定按钮点击
  const handleUpdate = async (values: TableListItem) => {
    if (values) {
      let width = 0;
      let height = 0;
      if (values.resolution != "other") {
        width = parseInt(values.resolution.split("x")[0]);
        height = parseInt(values.resolution.split("x")[1]);
      } else {
        width = parseInt(values.resolutionWidth);
        height = parseInt(values.resolutionHeight);
      }
      let rotationList = [
        {
          "tag": "config",
          "width": width,
          "height": height
        },
        {
          "id": "bgImage",
          "tag": "background",
          "html": `<li>
          <span class="del" style="display: none;">×</span>
          <div class="preview active"><svg viewBox="0 0 ${width} ${height}"><foreignObject width="${width}" height="${height}"><image style="background:#262732"></image></foreignObject></svg></div>
          <div class="duration"><span>时长</span>
          <div class="number">
          <div class="num-input-wrap">
          <input type="text" class="num-input" value="5">
          <span class="add"></span><span class="subtract">
          </span></div></div><span>秒</span></div></li>`,
          "duration": 0,
          "playList": [],
          "sizeList": []
        }
      ]
      let id = values.id;
      let programInfo = new Object();
      programInfo['name'] = values.name;
      programInfo['deviceType'] = values.deviceType;
      let resolution = values.resolution;
      let resolutionWidth;
      let resolutionHeight;
      if (resolution != '' && resolution != null && resolution != undefined) {
        if (resolution != 'other') {
          resolutionWidth = resolution.split('x')[0];
          resolutionHeight = resolution.split('x')[1];
        } else {
          resolutionWidth = values.resolutionWidth;
          resolutionHeight = values.resolutionHeight;
        }
      }

      let html = `<!doctype html>
      <html lang="zh">
      <head>
      <meta charset="utf-8"/>
      <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no,target-densitydpi=device-dpi"/>
      <meta name="theme-color" content="#000000"/>
      <title>智慧媒体管理系统</title>
      <style>
      body{margin:0}.body{position:absolute;width:100%;height:100%;left:0;top:0;} .previewContainer .body{position:relative;}#bgImage{width: 100%;height: 100%;object-fit: fill;pointer-events: none;}.body foreignObject,.body foreignObject textarea{border: none;pointer-events: none !important;position:relative}.body foreignObject img,.body foreignObject video{width:100%;height:100%;object-fit:contain;pointer-events: none;position:absolute}.body foreignObject video{position: absolute;z-index: 0;}foreignObject[tag="time"] .time{display: flex;width: 100%;height:100%;justify-content: center;align-items: center;text-align: center;position: absolute;}
      </style></head><body><div class="body">`+
        `<svg id="svgcontent" width="${resolutionWidth}" height="${resolutionHeight}" x="0" y="0" overflow="hidden" xmlns="http://www.w3.org/2000/svg" xmlns:se="http://svg-edit.googlecode.com" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 ${resolutionWidth} ${resolutionHeight}"><g style="pointer-events:none"><title style="pointer-events:inherit">画布</title><rect x="0" y="0" width="${resolutionWidth}" height="${resolutionHeight}" id="canvas_background" stroke-width="2" fill="#262732" style="pointer-events:inherit"></rect><image fill="transparent" stroke="#000" stroke-width="0" style="pointer-events:inherit" x="0" y="0" id="bgImage" width="${resolutionWidth}" height="${resolutionHeight}" xlink:href=""></image></g><g style="pointer-events:all"><title style="pointer-events:inherit">画布</title></g></svg>` +
        `</div></body></html>`;

      programInfo['resolutionWidth'] = resolutionWidth;
      programInfo['resolutionHeight'] = resolutionHeight;
      programInfo['template'] = values.template;
      programInfo['type'] = status;
      programInfo['totalTime'] = 0;
      programInfo['totalSize'] = 0;
      programInfo['previewImgUrl'] = '';
      programInfo['publishHtml'] = html;
      programInfo['editHtml'] = JSON.stringify(rotationList);
      programInfo['resourceIds'] = '';
      if (!id) {
        //新建节目
        addProgram(programInfo);
      } else {
        //编辑节目
        programInfo['id'] = id;
        save(programInfo);
      }
    }
  };

  //分配标签
  const assignTagCommand = (values: any) => {
    const tagsParam = new Object;
    tagsParam["ids"] = selectedRowKeys.toString();
    tagsParam["tagIds"] = values.toString();
    new Promise((resolve, reject) => {
      setTag(tagsParam)
        .then((res) => {
          if (res) {
            if (res.code === 200) {
              const hide = message.success('分配成功');
              handleAssignTagModalVisible(false);
              setSelectedRowKeys([]);
              setSelectedRows([]);
              actionRef.current?.reloadAndRest?.();
              hide();
              resolve(true);
            } else {
              message.error('分配失败，' + res.message);
              resolve(false);
            }
          }
        })
        .catch((error) => {
          message.error('删除失败');
          reject(error);
        });
    });
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '公告内容',
      dataIndex: 'name',
      ellipsis: true,
      width: 150,
      // renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
      //   if (type === 'form') {
      //     return null;
      //   }
      //   const status = form.getFieldValue('state');
      //   if (status !== 'open') {
      //     return (
      //       <Search
      //         placeholder="请输入节目名称"
      //         onSearch={debounce(value => { form.submit() }, 500)}
      //         onChange={debounce(value => { form.submit() }, 500)}
      //         style={{ width: 200 }}
      //       />
      //     );
      //   }
      //   return defaultRender(_);
      // },
      hideInSearch: true,
      valueType: 'text',
    },
    {
      title: '播放时间',
      dataIndex: 'time',
      // formItemProps: {
      //   rules: [
      //     {
      //       validator: (rule, value, callback) => {
      //         // console.log(value)
      //         if (value) {
      //           const n = (value.split('x')).length - 1;
      //           // console.log(n);
      //           if (n == 1) {
      //             callback();
      //           } else {
      //             callback("分辨率只能包含一个x，介于长和宽中间");
      //           }
      //         } else {
      //           callback();
      //         }
      //       },
      //     }
      //   ],
      // },
      // renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
      //   if (type === 'form') {
      //     return null;
      //   }
      //   const status = form.getFieldValue('state');
      //   if (status !== 'open') {
      //     return (
      //       <AutoComplete
      //         style={{ width: 200 }}
      //         options={[{ label: "全部分辨率", value: '' }, { value: '1920x1080' }, { value: '1080x1920' }]}
      //         onSelect={(value) => { form.submit() }}
      //       >
      //         <Input.Search
      //           allowClear
      //           placeholder="请输入分辨率"
      //           onSearch={(value) => { form.submit() }}
      //         />
      //       </AutoComplete>
      //     );
      //   }
      //   return defaultRender(_);
      // },
      hideInSearch: true,
      valueType: 'text',
    },
    {
      title: '公告状态',
      dataIndex: 'status',
      renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        const status = form.getFieldValue('state');
        if (status !== 'open') {
          return (
            <Select
              showSearch
              optionFilterProp="children"
              placeholder="请选择公告状态"
              style={{ width: 200 }}
              onChange={(value) => form.submit()}
            >
              <Option value="">所有</Option>
              <Option value="1">待发布</Option>
              <Option value="2">发布中</Option>
              <Option value="3">播放中</Option>
              <Option value="4">部分成功</Option>
              <Option value="5">部分失败</Option>
              <Option value="6">已结束</Option>
            </Select>
          );
        }
        return defaultRender(_);
      },
      valueEnum: {
        '1': { text: '待发布', status: 'Default' },
        '2': { text: '发布中', status: 'Processing' },
        '3': { text: '播放中', status: 'Processing' },
        '4': { text: '部分成功', status: 'Success' },
        '5': { text: '部分失败', status: 'Warning' },
        '6': { text: '已结束', status: 'Default' },
      },
    },
    // {
    //   title: '标签',
    //   dataIndex: 'tagIds',
    //   renderFormItem: (_, { type, defaultRender, ...rest }, form) => {
    //     if (type === 'form') {
    //       return null;
    //     }
    //     const status = form.getFieldValue('state');
    //     if (status !== 'open') {
    //       return (
    //         <TagCommonComponent
    //           topOrgId={JSON.parse(localStorage.getItem("user")).topOrgId}
    //           selectChange={(values) => selectChange(values, form)}
    //         >
    //         </TagCommonComponent>
    //       );
    //     }
    //     return defaultRender(_);
    //   },
    //   hideInTable: true,
    //   valueType: 'text',
    // },
    // {
    //   title: '标签',
    //   dataIndex: 'tags',
    //   valueType: 'text',
    //   width: 150,
    //   hideInSearch: true,
    //   render: tags => (
    //     <>
    //       {tags?.map((tag, index) => {
    //         return (
    //           <Tag color="blue" key={index} title={tag.name} style={{ marginBottom: 5, display: 'inline-block', overflow: 'hidden', whiteSpace: 'pre', textOverflow: 'ellipsis', maxWidth: 130 }}>
    //             {tag.name}
    //           </Tag>
    //         );
    //       })}
    //     </>
    //   ),
    // },
    {
      title: '作者',
      dataIndex: 'author',
      valueType: 'text',
      hideInSearch: true,
    },
    {
      title: '更新时间',
      dataIndex: 'updateDatetime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <>
          <a
            onClick={() => {
              handlePreviewModalVisible(true);
              setFormValues(record);
            }}
          >
            详情
          </a>
          <Divider type="vertical" />
          <a
            // disabled={record.status}
            onClick={() => design(record)}
          >
            编辑
          </a>
          <Divider type="vertical" />
          <a
            onClick={() => copy(record.id)}
          >
            复制
          </a>
          <Divider type="vertical" />
          <a onClick={() => publish(record)}>下线</a>
          <Divider type="vertical" />
          <a
            disabled={record.status}
            onClick={() => {
              delConfirm(record.id);
            }}
          >
            删除
          </a>
        </>
      ),
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        options={false}
        actionRef={actionRef}
        rowKey="key"
        search={{
          labelWidth: 120,
          // collapsed: false,
          // collapseRender:()=>false //隐藏收起按钮
        }}
        pagination={{ showQuickJumper: true, defaultPageSize: 10 }}
        toolBarRender={() => [
          <Button
            type="primary"
            onClick={() => {
              // handleModalVisible(true);
              // setProgramId("");
              history.push('/program/noticeList/new')
            }}
          >
            <PlusOutlined /> 新建
          </Button>,
          <Button
            type="primary"
            disabled={tagEnabled}
            onClick={() => handleAssignTagModalVisible(true)}
          >
            <TagsOutlined /> 分配标签
          </Button>,
          // <Button
          //   type="primary"
          //   disabled={selectedRows.length > 0 ? false : true}
          //   onClick={() => publishConfirm(selectedRows)}
          // >
          //   <MoreOutlined /> 批量发布
          // </Button>,
          <Button
            type="primary"
            disabled={selectedRows.length > 0 ? false : true}
            onClick={() => delConfirmBatch(selectedRows.map((row) => row.id).toString())}
          >
            <DeleteOutlined /> 批量删除
          </Button>,
        ]}
        request={(params, sorter, filter) => programList(params, sorter, filter)}
        columns={columns}
        onLoad={() => {
          setSelectedRowKeys(selectedRowKeys);
          setSelectedRows(selectedRows);
        }}
        rowSelection={{
          selectedRowKeys: selectedRowKeys,
          onSelect: (record, selected) => {
            if (selected) {//选中
              setSelectedRowKeys([...selectedRowKeys, record.key]);
              setSelectedRows([...selectedRows, record]);
            } else {//取消选中
              const newKeys = selectedRowKeys.concat();
              const index = newKeys.indexOf(record.key);
              newKeys.splice(index, 1);
              setSelectedRowKeys(newKeys);

              const newRows = selectedRows.concat();
              for (let i = 0; i < selectedRows.length; i++) {
                if (i == index) {
                  newRows.splice(index, 1);
                }
              }
              setSelectedRows(newRows);
            }
          },
          onSelectAll: (selected, selectedRows1, changeRows) => {
            if (selected) {//全选
              const keys = [];
              for (let i = 0; i < changeRows.length; i++) {
                const record = changeRows[i];
                keys.push(record.key);
              }
              setSelectedRowKeys([...selectedRowKeys, ...keys]);
              setSelectedRows([...selectedRows, ...changeRows]);
            } else {//取消全选
              const newSelectedRowKeys = selectedRowKeys.concat();
              const newSelectedRows = selectedRows.concat();
              for (let i = 0; i < changeRows.length; i++) {
                const record = changeRows[i];
                for (let j = 0; j < newSelectedRowKeys.length; j++) {
                  if (record.key == newSelectedRowKeys[j]) {
                    newSelectedRowKeys.splice(j, 1);
                    newSelectedRows.splice(j, 1);
                  }
                }
              }
              setSelectedRowKeys(newSelectedRowKeys);
              setSelectedRows(newSelectedRows);
            }
          }
        }}
        tableAlertOptionRender={() => {
          return (<a onClick={() => {
            setSelectedRowKeys([]);
            setSelectedRows([]);
            actionRef.current?.clearSelected?.();
          }}>清空</a>)
        }}
      />
      <CreateForm
        modalVisible={createModalVisible}
        id={programId}
        onSubmit={handleUpdate}
        onCancel={handleCancel}
      >
        <ProTable<TableListItem, TableListItem> />
      </CreateForm>
      <PreviewModel modalVisible={previewModalVisible} values={formValues} onCancel={handleClose}>
        <ProTable<TableListItem, TableListItem> />
      </PreviewModel>
      <AssignTagsModel
        modalVisible={assignTagModalVisible}
        topOrgId={topOrgId}
        onSubmit={assignTagCommand}
        onCancel={() => { handleAssignTagModalVisible(false); }}
      >
        <ProTable<TableListItem, TableListItem> />
      </AssignTagsModel>
      <PlanModel
        modalVisible={planModalVisible}
        id={formValues?.id}
        onCancel={() => handlePlanModalVisible(false)}
      >
        <ProTable<TableListItem, TableListItem> />
      </PlanModel>
      <Modal
        title="更新计划"
        visible={repackModalVisible}
        footer={repackFinish ? <Button onClick={() => handleRepackModalVisible(false)}>关闭</Button> : null}
        closable={false}
        className={styles.RepackPlanModel}
      >
        {repackPlanList.map(item => {
          return item.status == 'spinning' ? (
            <p key={item.id}>计划 {item.name} 更新中，请稍后...<Spin indicator={antIcon} style={{ marginLeft: 10 }} /></p>
          ) : (
            item.status == 'success' ? (
              <p key={item.id}>计划 {item.name} 更新完成<CheckCircleTwoTone twoToneColor="#52c41a" style={{ marginLeft: 10 }} /></p>
            ) : (
              <p key={item.id}>计划 {item.name} 更新失败<CloseCircleTwoTone twoToneColor="#ff4d4f" style={{ marginLeft: 10 }} /></p>
            )
          )
        }
        )}
      </Modal>
    </PageContainer>
  );
};

export default NoticeList;
